package com.spsoft.security.interceptor.handler;

import com.spsoft.core.annotation.AnonymousAccess;
import com.spsoft.core.config.VmsProperties;
import com.spsoft.core.enums.ResponseEnum;
import com.spsoft.core.exception.AuthException;
import com.spsoft.core.exception.LoginException;
import com.spsoft.core.model.bo.TokenUser;
import com.spsoft.core.utils.DateUtils;
import com.spsoft.core.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Order(1)
@Component
@Slf4j
public class TokenTimeOutHandler extends AbstractAuthorityHandler {

    @Autowired
    private  VmsProperties vmsProperties;
    @Override
    void processHandler(TokenUser user, HttpServletRequest request,AnonymousAccess authority) throws AuthException {
        try{
            Long loginTime = user.getLoginTime();
            String url= request.getServletPath();

          Long tokenExpireTime=  vmsProperties.getToknExpireTime();
            log.info("token 超时验证，用户:{}，创建时间：{},超时时间配置（秒）:{}"
                    ,user.getUserName()
                    ,DateUtils.formatDate(new Date(loginTime),DateUtils.NORM_DATETIME_PATTERN)
                    ,tokenExpireTime);

            if(tokenExpireTime==null ||tokenExpireTime==0 || "/login/refreshToken".equals(url)){
            return ;
            }
            if(System.currentTimeMillis() - loginTime > (tokenExpireTime*1000)|| StringUtil.isEmpty(user.getRefreshToken())){
              log.error("token 超时验证，用户:{}，创建时间(秒):{},当前时间秒：{},超时时间配置（秒）:{}"
                      ,user.getUserName()
                      ,loginTime/1000
                      ,System.currentTimeMillis()/1000
                      ,tokenExpireTime);
              throw new LoginException(ResponseEnum.TOKEN_TIME_OUT);
          };
        }catch (Exception e) {
            throw new LoginException(ResponseEnum.TOKEN_TIME_OUT);
        }

    }
}
